/*
 * Copyright (c) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "dyn_services_card_channel.h"

#include <securec.h>
#include <stddef.h>
#include <string.h>
#include <tee_defines.h>
#include <tee_internal_se_api.h>

#include "dyn_services_card_channel_inner.h"
#include "logger.h"

CardChannel *CreateSecureElementChannel(const char *readerName, const AppIdentifier *identifier)
{
    if (readerName == NULL || identifier == NULL || identifier->aid == NULL) {
        LOG_ERROR("invalid input aid, nullptr");
        return NULL;
    }

    if (identifier->aidLen <= AID_LENGTH_MIN || identifier->aidLen > AID_LENGTH_MAX) {
        LOG_ERROR("invalid input aid, length = %u", identifier->aidLen);
        return NULL;
    }

    SecureElementContext *context = CreateSecureElementContext(readerName, identifier);
    if (context == NULL) {
        LOG_ERROR("CreateSecureElementContext failed");
        return NULL;
    }
    ChannelOperations oper = {
        .open = SeChannelOpen,
        .openSecure = SeSecureChannelOpen,
        .close = SeChannelClose,
        .closeSecure = SeSecureChannelClose,
        .transmit = SeChannelTransmit,
        .getOpenResponse = SeChannelChannelGetOpenResponse,
    };

    CardChannel *channel = ConstructCardChannel(context, &oper);
    if (channel == NULL) {
        LOG_ERROR("malloc memory for card channel error");
        DestroySecureElementContext(context);
        return NULL;
    }
    return channel;
}

void DestroySecureElementChannel(CardChannel *channel)
{
    if (channel == NULL) {
        LOG_ERROR("channel is null");
        return;
    }
    if (channel->context != NULL) {
        DestroySecureElementContext(channel->context);
        channel->context = NULL;
    }
    DestructCardChannel(channel);
}
